package com.yungam.other.mes_controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.yungam.common.bean.equip.Equipment;
import com.yungam.common.service.EquipmentService;
import com.yungam.exception.bean.BusinessException;
import com.yungam.exception.bean.ErrorCodeEnum;
import com.yungam.other.service.IotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取设备最新状态信息接口
 */
@Slf4j
@RestController
public class MachineStatusController {

    @Resource
    private EquipmentService equipmentService;
    @Resource
    private IotService iotService;

    @GetMapping("/IMCS/getMachineStatus")
    public List<Map<String, Object>> getMachineStatus() {
        log.info("『Mes 调用』获取设备最新状态信息接口");
        List<Map<String, Object>> ans = new ArrayList<>();
        List<Map<String, Object>> equipsState = iotService.getEquipsState();
        if (equipsState == null) {
            log.info("从IOT查询到的设备状态数据为空");
            throw new BusinessException(ErrorCodeEnum.SYSTEM_ERROR, "从IOT查询到的设备状态数据为空");
        }
        Map<String, Integer> stateMap = Maps.newHashMap();
        for (Map<String, Object> map : equipsState) {
            Integer value = (Boolean) map.get("equipOnline") ? 1 : 0;
            stateMap.put((String) map.get("equipIp"), value);
        }
        QueryWrapper<Equipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(Equipment.class, col -> !col.getProperty().equals("equImg"));
        List<Equipment> list = equipmentService.list(queryWrapper);
        for (Equipment equipment : list) {
            Map<String, Object> map = new HashMap<>();
            Integer state = stateMap.getOrDefault(equipment.getEquIp(), 0);
            map.put("eqptNo", equipment.getEquNumber());     // 设备编号
            map.put("eqptStatus", state);  // 设备状态
            ans.add(map);
        }
        log.info("『Mes 调用』获取设备最新状态信息接口成功");
        log.info("『返回数据』{}", new Gson().toJson(ans));
        return ans;
    }

}
